<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>点评</title>
  <link rel="stylesheet" href="./css/base.css">
  <link rel="stylesheet" href="./css/comment-add.css">
</head>

<body>
  <div class="passport-info">
    <div class="line clearfix">
      <span class="line-left float-l">护照号No.
        <sup>*</sup>
      </span>
      <div class="line-right float-r">
        <input id="passportNo" type="text" placeholder="请输入护照号">
      </div>
    </div>
  </div>
  <div class="common-tags">
    <a class="tag">逃跑</a>
    <a class="tag">偷窃</a>
    <a class="tag">不服雇主安排</a>
    <a class="tag">隐瞒身体疾病</a>
  </div>
  <div class="comment-container">
    <h3>添加评论：</h3>
    <div class="comment-wrapper">
      <textarea maxlength="120" name="comment" id="comment" cols="30" rows="6" placeholder="请输入评论"></textarea>
      <p class="comment-info">
        <span id="words-number">0</span> / 120</p>
    </div>
  </div>
  <div class="upload-img">
    <h3>上传护照照片</h3>
    <div class="img-container clearfix">
      <div class="img-wrapper float-l">
        <input id="imgFile" type="file">
        <img id="img" src="./img/add-img.png" alt="">
        <a class="delete-img">
          <img src="./img/delete.png" alt="">
        </a>
      </div>
    </div>
  </div>
  <div class="control-field">
    <a id="submit" class="active">提 交</a>
  </div>
  <div class="mask"></div>
  <div class="verification">
    <h3>手机验证</h3>
    <div class="input-wrapper clearfix">
      <label for="mobile">手机号：</label>
      <input id="mobile" name="mobile" type="text">
    </div>
    <div class="input-wrapper clearfix">
      <label for="message-code">验证码：</label>
      <input id="message-code" name="message-code" type="text">
      <a id="send-code">发 送</a>
    </div>
    <div class="alert-container">
        <p class="alert-message">验证码已发送</p>
    </div>
    <a id="confirm">确 定</a>
  </div>
</body>
</html>
<script type="text/javascript" src="./js/index.js"></script>
<script>
  window.onload = function(){
    var passport = document.getElementById("passportNo"),
        comment = document.getElementById("comment"),
        tagNodeList = document.getElementsByClassName("tag"),
        imgFile = document.getElementById("imgFile"),
        img = document.getElementById("img"),
        submit = document.getElementById("submit"),
        words_number = document.getElementById("words-number"),
        mask = document.getElementsByClassName("mask")[0],
        verification = document.getElementsByClassName("verification")[0],
        mobile = document.getElementById("mobile"),
        message_code = document.getElementById("message-code"),
        send_code = document.getElementById("send-code"),
        alertMessage = document.getElementsByClassName("alert-message")[0],
        confirm = document.getElementById("confirm");
  
    function initPassport() {
      if (parameterFromUrl("passportNo")) {
        let passportNo = parameterFromUrl("passportNo");
        // history.replaceState(null,null,location.href.split("#")[0] + "")
        passport.value = passportNo;
      } else {
        return false;
      }
    }

    initPassport()

    for (i = 0; i < tagNodeList.length; i++) {
      tagNodeList[i].onclick = function () {
        // console.log(this.className)
        if (this.className.indexOf("active") > -1) {
          this.classList.remove("active")
        } else {
          this.classList.add("active")
        }
      }
    }

    comment.oninput = wordsCount;

    function wordsCount() {
      words_number.innerText = comment.value.length
    }

    
    let tagStr = "";
    
    // 显示手机验证弹窗
    submit.onclick = verifyMobile;
    
    function verifyMobile() {
      tagStr = "";
      let activeTagList = document.getElementsByClassName("tag active");
      for(j=0;j<activeTagList.length;j ++){
        tagStr += activeTagList[j].innerText + ","
      }

      if(passport.value.trim() == ""){
        alert("请填写护照号！")
      }else if(tagStr == "" && comment.value.trim() ==""){
        alert("请填写评论！")
      }else{
        mask.style.display = "block";
        verification.style.display = "block";
      }
    }

    // 关闭手机验证弹窗
    mask.onclick = function(){
      mask.style.display = "none";
      verification.style.display = "none";
    }

    // 隐藏错误提示
    mobile.oninput = hideAlert;
    message_code.oninput = hideAlert;
    function hideAlert(){
      alertMessage.innerText = "";
      alertMessage.style.display = "none";
      // console.log("hide")
    }

    // 发送验证码
    send_code.addEventListener("click", sendCode)
    
    function sendCode(){
      hideAlert();
      let mobileNum = mobile.value.trim();
      if(mobileNum == ""){
        alertMessage.innerText = "手机号不能为空！";
        alertMessage.style.display = "block";
        return;
      }else if(!(/^1[3-9]\d{9}$/.test(mobileNum))){
        alertMessage.innerText = "您输入的手机号有误！";
        alertMessage.style.display = "block";
        return;
      }else{
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          console.log(xhr)

          if(xhr.readyState == 4){
            if(xhr.status == 200){
              var res = JSON.parse(xhr.responseText);
              
              // 开始发送
              if(res.code == 0){
                send_code.removeEventListener("click", sendCode)
                var count = 60;
                send_code.style.backgroundColor = "#999";
                send_code.innerText = count;
                var countDown = setInterval(function () {
                  count--;
                  send_code.innerText = count;
                  if (count <= 0) {
                    clearInterval(countDown);
                    send_code.style.backgroundColor = "#FF5E5E";
                    send_code.innerText = "发 送";
                    send_code.addEventListener("click", sendCode)
                  }
                }, 1000)
              }else{
                alertMessage.innerText = "发送验证码失败！";
                alertMessage.style.display = "block";
                return;
              }
            }else{
              alertMessage.innerText = "发送请求失败！";
              alertMessage.style.display = "block";
              return;
            }
          }
        }

        xhr.open("POST", api+"/comment/mobileRegister");
        let reqData = JSON.stringify({mobile:mobileNum})
        xhr.send(reqData)
      }
    }

    // 提交评论
    confirm.onclick = submitComment;

    function submitComment() {
      hideAlert();
      let passportNo = passport.value.trim(),
          comment_val = tagStr + comment.value.trim(),
          img_file = imgFile.files[0],
          mobileNum = mobile.value.trim(),
          messageCode = message_code.value.trim();

      if(mobileNum == ""){
        alertMessage.innerText = "手机号不能为空！";
        alertMessage.style.display = "block";
        return;
      }else if(!(/^1[3-9]\d{9}$/.test(mobileNum))){
        alertMessage.innerText = "您输入的手机号有误！";
        alertMessage.style.display = "block";
        return;
      }else if(messageCode == ""){
        alertMessage.innerText = "验证码不能为空！";
        alertMessage.style.display = "block";
        return;
      }else if(messageCode.length != 6){
        alertMessage.innerText = "您输入的验证码有误！";
        alertMessage.style.display = "block";
        return;
      }else{
        let formData = new FormData();
      
        formData.append("passportNo", passportNo);
        formData.append("comment", comment_val);
        formData.append("comment_pic", img_file);
        formData.append("user_name", mobileNum);
        formData.append("message_code", messageCode)

        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if(xhr.readyState == 4){
            if(xhr.status == 200){
              var res = JSON.parse(xhr.responseText);
              if(res.code == "0"){
                alertMessage.innerText = res.reason;
                alertMessage.style.display = "block";
                location.replace("./comments.html?passportNo="+passportNo)
                return;
              }else if(res.code == "1"){
                alertMessage.innerText = res.reason;
                alertMessage.style.display = "block";
                return;
              }
            }else{
              alertMessage.innerText = "发送请求失败!";
              alertMessage.style.display = "block";
              return;
            }
          }
        }

        xhr.open("POST", api+"/comment/savecomment");
        xhr.send(formData)
      }
    }

    // 上传图片
    img.onclick = function(){
      imgFile.click()
    }

    imgFile.onchange = function(){
      // console.dir(imgFile)
      let img_txt;
      // 验证图片格式
      if(!imgFile.value.match(/.jpg|.jpeg|.gif|.png|.bmp/i) && imgFile.value) return alert("您上传的图片格式不正确，请重新选择！"), !1;
      if(imgFile.files && imgFile.files[0]){
        img.src = window.navigator.userAgent.indexOf("Chrome") >= 1 || window.navigator.userAgent.indexOf("Safari") >= 1 ? window.webkitURL.createObjectURL(imgFile.files[0]) : window.URL.createObjectURL(imgFile.files[0]);
      }
    }
  }
</script>